<script setup>
import { ref, onMounted, onBeforeMount, reactive, nextTick, inject } from 'vue';
import { showToast, showDialog } from 'vant';
import {
    getUrlParam,
    navigateTo,
    silentLogin,
    getAuthUrl,
    checkEnvConfig,
    wxHideOptionMenu,
    getMapping
} from '@/utils';
import { PGuide } from '../components';
import CodePay from '../code-pay/index.vue';
import OrderPay from '../order-pay/index.vue';
import GroupPay from '../group-pay/index.vue';
import store from '@/utils/store';
import api from '@/api';

const isDebug = import.meta.env.VITE_ENABLE_ERUDA;
const orderPayRef = ref(null);
const groupPayRef = ref(null);
const codePayRef = ref(null);
const $logger = inject('logger');

const state = reactive({
    showLoading: true,
    payMoney: '',
    appId: '', // H5 认证appid
    h5PayMerchantNo: '', // H5 对应商户号
    showGuide: true,
    errorInfo: null,
    payType: ''
});

onBeforeMount(() => {
    // pc方便调试用，正式环境不会读此处
    if (import.meta.env.VITE_DEBUG) {
        store.set('USERINFO', {
            buyerFlag: true,
            deviceId: 12315,
            headerImg:
                'https://public-1256988483.cos.ap-guangzhou.myqcloud.com/lIYozVxpauEC5bab0a29107085a6fe3cfd64668722f9.jpg',
            nickName: '刚刚',
            openId: 'omQKJ6wPQLWqJI6CFqA5Jxa7WkL8',
            token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjb20uYnVzaW5lc3MiLCJleHAiOjE3NjMyOTY4NDcsImlhdCI6MTc2MDcwNDg0NywidXNlcklkIjoxMDI0MDEwNTAwMDUwMDAwMTY4fQ.7fHuYK3HVS8ppSk7lKYGJLQogx1KcpQvij6FY4l1ctY',
            tokenExpiresTime: 1763296847509,
            userId: '1024010500050000168',
            userStatus: 'AUTHED'
        });
    }
    wxHideOptionMenu();
});

/**
 * 流程：
 * 1、进入页面后，先判断环境是否微信下面打开，是微信环境正常展示，否则拦截显示
 * 2、静默授权返回code，通过code登录返回用户信息USERINFO，通过store缓存
 * 3、若授权失效，用户点击付款时，未授权主动在auth页授权登录后返回处理, 刷新页面时可能storeAppId 与 appId 不相等时重新走静默授权
 *
 *  payType 区分业务类型
 *      code: 收款码支付
 *          传入参数有 turId appRoute
 *      order: 开单收款支付
 *          传入参数有 turId orderId appRoute
 *      group: 团购接龙支付
 *          传入参数有 turId relayId appRoute
 *
 */

onMounted(async () => {
    try {
        const payType = getUrlParam('payType') || 'code';
        let turId = getUrlParam('turId') || '';
        let orderId = getUrlParam('orderId') || '';
        let relayId = getUrlParam('relayId') || '';
        let appRoute = getUrlParam('appRoute') || '';
        const jsCode = getUrlParam('code');
        const isWxEnv = checkEnvConfig();

        // 判断业务类型
        state.payType = payType;
        const mapId = getUrlParam('mapId') || '';
        // 根据映射id获取码的参数
        if (mapId) {
            // store.set('MAP_ID', mapId);
            try {
                const mapData = await getMapping(mapId);
                if (mapData) {
                    turId = mapData.turId || '';
                    orderId = mapData.orderId || '';
                    relayId = mapData.relayId || '';
                    appRoute = mapData.appRoute || '';
                }
            } catch (err) {
                showToast('获取映射信息失败');
                console.log(err);
            }
        }

        if (isWxEnv) {
            state.showGuide = false;
            const appId = await getPayInfo(turId);
            if (!appId) {
                return;
            }
            const userInfo = store.get('USERINFO');
            const authType = store.get('LOGIN_SCOPE');
            const storeAppId = store.get('APP_ID');
            // 用户主动在auth页授权登录后返回, 刷新页面时可能storeAppId 与 appId 不相等时重新走静默授权
            if (authType === 'userinfo' && userInfo && storeAppId === appId && appId) {
                store.remove('LOGIN_SCOPE');
                state.showGuide = false;
                window.history.replaceState(
                    {},
                    '',
                    `?payType=${payType}&turId=${turId}&orderId=${orderId}&relayId=${relayId}&appRoute=${appRoute}`
                );
                if (payType === 'order') {
                    // 开单收款付款
                    orderPayRef.value.authBackAction();
                } else if (payType === 'group') {
                    // 团队接龙付款
                    groupPayRef.value.authBackAction();
                } else {
                    // 收款码付款
                    codePayRef.value.authBackAction();
                }
                return;
            }
            // 静默授权后回调返回code进行登录
            if (jsCode && storeAppId === appId && appId) {
                if (
                    !userInfo ||
                    (userInfo &&
                        userInfo.tokenExpiresTime - 24 * 60 * 60 * 1000 <= new Date().getTime())
                ) {
                    await silentLogin(jsCode);
                }
                state.showGuide = false;
                getInitData();
                return;
            } else {
                // 静默授权
                const appRoute = getUrlParam('appRoute');
                if (!turId && payType === 'code') {
                    showDialog({
                        title: '收款码异常，缺少必要信息',
                        confirmButtonText: '确定'
                    });
                    return;
                }
                appId && store.set('APP_ID', appId);
                // 每次静默授权，删除缓存userInfo，确保每次获取的openId为最新
                store.remove('USERINFO');
                const authUrl = getAuthUrl(
                    `?turId=${turId}&orderId=${orderId}&relayId=${relayId}&payType=${payType}&appRoute=${appRoute}`
                );
                store.set('LOGIN_SCOPE', 'silent');
                navigateTo(authUrl, { routerType: 'replace', isBlank: true });
            }
        } else {
            window.history.replaceState(
                {},
                '',
                `?payType=${payType}&turId=${turId}&orderId=${orderId}&relayId=${relayId}&appRoute=${appRoute}`
            );
            // pc浏览器调试
            if (import.meta.env.VITE_DEBUG) {
                const userInfo = store.get('USERINFO');
                if (userInfo) {
                    state.showGuide = false;
                    const curAppId = await getPayInfo(turId);
                    curAppId && store.set('APP_ID', curAppId);
                    getInitData();
                } else {
                    state.showLoading = false;
                }
            } else {
                state.showLoading = false;
            }
        }
    } catch (err) {
        showToast('payment页面异常，请稍后再试');

        $logger.error(err, {
            pageId: 10000,
            moduleCode: 'USER',
            tag: 'payment页面进入异常',
            uri: 'views/order/payment/index.vue'
        });
    }
});

/**
 * 初始化请求信息
 */
const getInitData = () => {
    const payType = getUrlParam('payType') || 'code';
    nextTick(() => {
        if (payType === 'order') {
            orderPayRef.value.getOrderInfo();
        } else if (payType === 'group') {
            groupPayRef.value.getGroupInfo();
        } else {
            codePayRef.value.getCodeInfo();
        }
    });
};

/**
 * 获取h5支付的appid和商户号
 */
const getPayInfo = async (turId) => {
    try {
        const res = await api.fetchGet('getOfficialAccountPayInfo', { turId }, { hasErr: true });
        const { code, data, message } = res || {};
        state.showLoading = false;
        if (code === 0) {
            const { h5PayMerchantNo, appId } = data;
            state.appId = appId;
            state.h5PayMerchantNo = h5PayMerchantNo;
            return appId;
        } else if (code === 2006101 || code === 4009016) {
            // 未获取到可用通道 2006101
            // MA绑定异常 4009016
            state.errorInfo = {
                iconName: 'info1',
                title: message,
                infoText: '请通知商家联系生意云客服'
            };
        } else if (code === 4008012) {
            // 请通知商家申请微信商户号
            state.errorInfo = {
                iconName: 'guard1',
                title: message,
                infoText: '应监管要求，需申请微信商户号后可收款'
            };
        } else {
            showToast(message);
            return '';
        }
    } catch (err) {
        state.showLoading = false;
        console.log(err);
        showToast('获取支付appId失败');
        $logger.error(err, {
            pageId: 10000,
            moduleCode: 'PAYMENT',
            tag: 'getOfficialAccountPayInfo接口异常',
            uri: 'order/collectMoney/collect/getOfficialAccountPayInfo'
        });
        return '';
    }
};

const handleClearStore = () => {
    store.clearAll();
};
</script>

<template>
    <!-- 调试按钮 -->
    <van-button type="warning" class="debug-class" v-if="isDebug" @click="handleClearStore">
        清除缓存
    </van-button>
    <!-- 页面效果 -->
    <c-page :loading="state.showLoading">
        <!-- 非微信环境拦截 -->
        <p-guide :show="state.showGuide"></p-guide>
        <!-- 请求异常显示效果 -->
        <c-result
            v-if="!state.showGuide && state.errorInfo"
            :icon-name="state.errorInfo.iconName"
            :icon-color="state.errorInfo.iconColor"
            :title="state.errorInfo.title"
            :info-text="state.errorInfo.infoText"
            :btn-type="state.errorInfo.btnType"
            :btn-name="state.errorInfo.buttonName"
        ></c-result>
        <!-- 收款码 -->
        <CodePay
            ref="codePayRef"
            :merchant-no="state.h5PayMerchantNo"
            v-if="state.payType === 'code' && !state.showGuide && !state.errorInfo"
        ></CodePay>
        <!-- 开单收款 -->
        <OrderPay
            ref="orderPayRef"
            :merchant-no="state.h5PayMerchantNo"
            v-if="state.payType === 'order' && !state.showGuide && !state.errorInfo"
        ></OrderPay>
        <!-- 团购接龙 -->
        <GroupPay
            ref="groupPayRef"
            :merchant-no="state.h5PayMerchantNo"
            v-if="state.payType === 'group' && !state.showGuide && !state.errorInfo"
        ></GroupPay>
    </c-page>
</template>

<style scoped lang="less">
@import './index.less';
</style>
